import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../l10n/app_localizations.dart';

/// 网页浏览页面
/// 用于显示隐私政策、用户协议等网页内容
class WebViewPage extends StatefulWidget {
  final String url;
  final String? title;

  const WebViewPage({super.key, required this.url, this.title});

  @override
  State<WebViewPage> createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  late final WebViewController _controller;
  bool _isLoading = true;
  String? _pageTitle;
  @override
  void initState() {
    super.initState();
    _initializeWebView();
  }

  void _initializeWebView() {
    print('widget.url: ${widget.url}');
    _controller =
        WebViewController()
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..setNavigationDelegate(
            NavigationDelegate(
              onPageStarted: (String url) {
                setState(() {
                  _isLoading = true;
                });
              },
              onPageFinished: (String url) async {
                setState(() {
                  _isLoading = false;
                });
                // 尝试获取页面标题
                try {
                  final title = await _controller.getTitle();
                  if (title != null && title.isNotEmpty) {
                    setState(() {
                      _pageTitle = title;
                    });
                  }
                } catch (e) {
                  // 忽略获取标题失败
                }
              },
              onWebResourceError: (WebResourceError error) {
                print('网页加载错误: ${error.description}');
              },
            ),
          )
          ..loadRequest(Uri.parse(widget.url));
  }

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context);
    final displayTitle =
        widget.title ?? _pageTitle ?? localizations.privacyPolicy;

    return Scaffold(
      backgroundColor: const Color(0xFF0A0E27),
      appBar: AppBar(
        backgroundColor: const Color(0xFF1A1F3A),
        elevation: 0,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.white, size: 20.sp),
          onPressed: () => Get.back(),
        ),
        title: Text(
          displayTitle,
          style: TextStyle(
            color: Colors.white,
            fontSize: 18.sp,
            fontWeight: FontWeight.bold,
          ),
        ),
        centerTitle: true,
      ),
      body: Stack(
        children: [
          // WebView
          WebViewWidget(controller: _controller),

          // 加载指示器
          if (_isLoading)
            Container(
              color: const Color(0xFF0A0E27),
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    CircularProgressIndicator(
                      valueColor: AlwaysStoppedAnimation<Color>(
                        const Color(0xFF05FFFD),
                      ),
                    ),
                    SizedBox(height: 16.h),
                    Text(
                      '加载中...',
                      style: TextStyle(
                        color: const Color(0xFF05FFFD),
                        fontSize: 14.sp,
                      ),
                    ),
                  ],
                ),
              ),
            ),
        ],
      ),
    );
  }
}
